package nvr

import (
	"encoding/xml"
	"errors"
	"fmt"
	"strings"
	"time"

	http_label_center "gobase/http_work_flow/label_center"
	"gobase/logger"
)

// 布防类型
const (
	GuardType移动侦测 = 1 + iota
	GuardType遮挡
	GuardType进入
	GuardType离开
)

// 请求设备布防信息
type ReqGetNvrGuardRecDeviceTag struct {
	DeviceId  string `json:"DeviceId"`  //国标ID
	TypeGuard int8   `json:"TypeGuard"` //布防类型
	RegionId  int8   `json:"RegionId"`  //进入、离开 区域编号
}

// 设备报警消息
type ReqCreateNvrAlarmRecDeviceTag struct {
	DeviceId  string    `json:"DeviceId"`  //国标ID
	TypeAlarm int8      `json:"TypeAlarm"` //报警类型
	RegionId  int8      `json:"RegionId"`  //进入、离开 区域编号
	TimeAlarm time.Time `json:"TimeAlarm"` //报警时间
}

// // 设备报警消息
// type RespAlarmRecDeviceTag struct {
// 	JsonTag   string `json:"JsonTag"`   // http_label_center.Tag
// 	JsonAlarm string `json:"JsonAlarm"` // AlarmReport
// }

// XML2DrawFrame 中间数据转绘制
func XML2Frame(guard_msg map[string]Msg, guard_type int8, region_id int8) (_frame http_label_center.Tag, _err error) {
	if guard_type == 0 {
		return http_label_center.Tag{}, errors.New("guard_type is 0")
	}
	var xmlStruct = XmlStruct{}
	var guardMsg Msg
	for _, m := range guard_msg {
		if m.GuardType == guard_type {
			guardMsg = m
			break
		}
	}

	if guardMsg.GuardType != guard_type {
		return http_label_center.Tag{}, fmt.Errorf("guard_type is not match guardMsg.GuardType:[%d]", guardMsg.GuardType)
	}
	guardMsg.GuardInfo = strings.Replace(guardMsg.GuardInfo, "\n", "", -1)
	var metas []http_label_center.Meta
	switch guardMsg.GuardType {
	case GuardType移动侦测:
		_err = xml.Unmarshal([]byte(guardMsg.GuardInfo), &xmlStruct.MotionDetection) //移动侦测
		if _err != nil {
			_err = fmt.Errorf("msg 解析错误")
			return
		}
		//移动侦测
		if xmlStruct.MotionDetection.MotionDetectionLayout.Layout.GridMap != "" {
			metas = append(metas, http_label_center.Meta{
				X:           0,
				Y:           0,
				StrokeStyle: "rgb(255,0,0)",
				LineWidth:   1,
				Remark:      "移动侦测网格",
				TypeId:      GuardType移动侦测,
				Grid: &http_label_center.Grid{
					Map:    xmlStruct.MotionDetection.MotionDetectionLayout.Layout.GridMap,
					Column: xmlStruct.MotionDetection.Grid.ColumnGranularity,
					Row:    xmlStruct.MotionDetection.Grid.RowGranularity,
				},
			})
		} else {
			logger.Debugf("GridMap:%+v", xmlStruct.MotionDetection)
		}
	case GuardType遮挡:
		_err = xml.Unmarshal([]byte(guardMsg.GuardInfo), &xmlStruct.TamperDetection) //遮挡
		if _err != nil {
			_err = fmt.Errorf("msg 解析错误")
			return
		}
		//遮挡
		for _, region := range xmlStruct.TamperDetection.TamperDetectionRegionList.TamperDetectionRegion {
			if len(region.RegionCoordinatesList.RegionCoordinates) == 0 {
				continue
			}
			var pens []http_label_center.Pen
			for k, p := range region.RegionCoordinatesList.RegionCoordinates {
				if k == 0 {
					continue
				}
				pens = append(pens, http_label_center.Pen{
					X: p.PositionX,
					Y: xmlStruct.TamperDetection.NormalizedScreenSize.NormalizedScreenHeight - p.PositionY,
				})
			}
			metas = append(metas, http_label_center.Meta{
				X:           region.RegionCoordinatesList.RegionCoordinates[0].PositionX,
				Y:           xmlStruct.TamperDetection.NormalizedScreenSize.NormalizedScreenHeight - region.RegionCoordinatesList.RegionCoordinates[0].PositionY,
				StrokeStyle: "rgb(255,0,0)",
				LineWidth:   1,
				Fill:        true,
				FillStyle:   "gray",
				Remark:      "遮挡",
				TypeId:      GuardType遮挡,
				ProtoWidth:  xmlStruct.TamperDetection.NormalizedScreenSize.NormalizedScreenWidth,
				ProtoHeight: xmlStruct.TamperDetection.NormalizedScreenSize.NormalizedScreenHeight,
				Pen:         &pens,
			})
		}
	case GuardType进入:
		_err = xml.Unmarshal([]byte(guardMsg.GuardInfo), &xmlStruct.RegionEntrance) //进入
		if _err != nil {
			_err = fmt.Errorf("msg 解析错误")
			return
		}
		//进入
		for _, region := range xmlStruct.RegionEntrance.RegionEntranceRegionList.RegionEntranceRegion {
			if len(region.RegionCoordinatesList.RegionCoordinates) == 0 {
				continue
			}
			if region_id != 0 && int8(region.Id) != region_id {
				continue
			}
			var pens []http_label_center.Pen
			for k, p := range region.RegionCoordinatesList.RegionCoordinates {
				if k == 0 {
					continue
				}
				pens = append(pens, http_label_center.Pen{
					X: p.PositionX,
					Y: xmlStruct.RegionEntrance.NormalizedScreenSize.NormalizedScreenHeight - p.PositionY,
				})
			}
			metas = append(metas, http_label_center.Meta{
				X:           region.RegionCoordinatesList.RegionCoordinates[0].PositionX,
				Y:           xmlStruct.RegionEntrance.NormalizedScreenSize.NormalizedScreenHeight - region.RegionCoordinatesList.RegionCoordinates[0].PositionY,
				StrokeStyle: "yellow",
				Remark:      "进入",
				TypeId:      GuardType进入,
				ProtoWidth:  xmlStruct.RegionEntrance.NormalizedScreenSize.NormalizedScreenWidth,
				ProtoHeight: xmlStruct.RegionEntrance.NormalizedScreenSize.NormalizedScreenHeight,
				Pen:         &pens,
			})
		}
	case GuardType离开:
		_err = xml.Unmarshal([]byte(guardMsg.GuardInfo), &xmlStruct.RegionExiting) //退出
		if _err != nil {
			_err = fmt.Errorf("msg 解析错误")
			return
		}
		//离开
		for _, region := range xmlStruct.RegionExiting.RegionExitingRegionList.RegionExitingRegion {
			if len(region.RegionCoordinatesList.RegionCoordinates) == 0 {
				continue
			}
			if region_id != 0 && int8(region.Id) != region_id {
				continue
			}
			var pens []http_label_center.Pen
			for k, p := range region.RegionCoordinatesList.RegionCoordinates {
				if k == 0 {
					continue
				}
				pens = append(pens, http_label_center.Pen{
					X: p.PositionX,
					Y: xmlStruct.RegionExiting.NormalizedScreenSize.NormalizedScreenHeight - p.PositionY,
				})
			}
			metas = append(metas, http_label_center.Meta{
				X:           region.RegionCoordinatesList.RegionCoordinates[0].PositionX,
				Y:           xmlStruct.RegionExiting.NormalizedScreenSize.NormalizedScreenHeight - region.RegionCoordinatesList.RegionCoordinates[0].PositionY,
				StrokeStyle: "yellow",
				Remark:      "离开",
				TypeId:      GuardType离开,
				ProtoWidth:  xmlStruct.RegionExiting.NormalizedScreenSize.NormalizedScreenWidth,
				ProtoHeight: xmlStruct.RegionExiting.NormalizedScreenSize.NormalizedScreenHeight,
				Pen:         &pens,
			})
		}
	default:
		_err = fmt.Errorf("guardType:[%d] 不存在", guardMsg.GuardType)
		return
	}
	if len(metas) == 0 {
		_err = fmt.Errorf("获取布防信息为空")
		return
	}
	_frame.Metas = metas
	return
}
